package core.auth;

import core.util.ConstDefine;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by Bowen on 2014/8/8.
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    /**
     * 不过滤路径
     */
    private List<String> excludeUrls;

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HttpSession session = request.getSession();
        String contextPath = request.getContextPath();

        String servletPath = request.getServletPath();

        //排除拦截的地址
        for (String url : excludeUrls) {
            if (servletPath.contains(url)) {
                return true;
            }
        }

        //自动跳转到登录页面
        if (servletPath.equals("/")) {
            response.sendRedirect(contextPath + "/login");
            return false;
        }

        //登录验证
        if (servletPath.equals("/preLogin")) {
            return true;
        }
        if (servletPath.equals("/logout")) {
            Enumeration e = session.getAttributeNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                session.removeAttribute(name);
            }
            response.sendRedirect(contextPath + "/login");
            return false;
        }
        if (!servletPath.equals("/login")) {
            if (null==session.getAttribute(ConstDefine.LOGIN_SESSION_NAME)) {
                response.sendRedirect(contextPath + "/login");
                return false;
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
